package com.ecoolex.discount.sales.core.manager;

import com.ecoolex.discount.sales.core.dao.DiscountProductAttachDAO;
import com.ecoolex.discount.sales.entity.DiscountProductAttach;
import com.ecoolex.discount.sales.entity.DiscountProductAttach.Column;
import com.ecoolex.discount.sales.entity.DiscountProductAttachExample;
import com.ecoolex.discount.sales.entity.DiscountProductAttachExample.Criteria;
import com.ecoolex.discount.sales.pojo.EditDiscountProductAttachDTO;
import com.ecoolex.framework.common.enums.ResultCode;
import com.ecoolex.framework.common.exception.BizException;
import com.ecoolex.framework.common.util.BizAssert;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.CollectorUtil;

import java.time.Instant;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DiscountProductAttachManager {
	
    @Autowired
    private DiscountProductAttachDAO dao;
    
    public void updateProductAttach(Integer productId, List<EditDiscountProductAttachDTO> attachList, String updateUser) throws BizException {
    	List<DiscountProductAttach> oldList = listByMainProductId(productId);
    	for (EditDiscountProductAttachDTO dto : attachList) {
			//修改
    		if(Check.notNull(dto.getId())) {
    			DiscountProductAttach old = oldList.stream().collect(CollectorUtil.first(o -> dto.getId().equals(o.getId())));
    			BizAssert.isTrue(Check.notNull(old),ResultCode.VERIFY.build(10), "折扣附加产品不存在，Id={}",dto.getId());
    			oldList.remove(old);
    		}else {//新增
				DiscountProductAttach record = new DiscountProductAttach();
				record.setMainProductId(productId);
				record.setAttachProductId(dto.getAttachProductId());
				record.setDeleted(DiscountProductAttach.NOT_DELETED);
				record.setCreateTime(Date.from(Instant.now()));
				record.setCreateUser(updateUser);
				record.setUpdateTime(Date.from(Instant.now()));
				record.setUpdateUser(updateUser);
				dao.insert(record);
			}
		}
    	oldList.forEach(old -> {
    		delete(old, updateUser);
    	});
	}
    
    public List<DiscountProductAttach> listByMainProductId(Integer mainProductId){
    	DiscountProductAttachExample example = new DiscountProductAttachExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andMainProductIdEqualTo(mainProductId).andDeletedEqualTo(DiscountProductAttach.NOT_DELETED);
    	return dao.selectByExample(example);
    }
    
    public DiscountProductAttach get(Integer id) {
    	return dao.selectByPrimaryKeyWithLogicalDelete(id, DiscountProductAttach.NOT_DELETED);
    }
    
    public void delete(DiscountProductAttach record,String updateUser) {
    	record.setDeleted(DiscountProductAttach.IS_DELETED);
    	record.setUpdateTime(Date.from(Instant.now()));
		record.setUpdateUser(updateUser);
		dao.updateByPrimaryKeySelective(record, Column.deleted,Column.updateUser,Column.updateTime);
    }
}